package com.example.mvplibrary.mvplibrary.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;

import com.example.mvplibrary.mvplibrary.model.BaseModel;
import com.example.mvplibrary.mvplibrary.presenter.BasePresenter;
import com.example.mvplibrary.mvplibrary.ui.fragment.BaseFragment;
import com.example.mvplibrary.mvplibrary.view.BaseView;

public abstract class BaseLazyFragment<V extends BaseView,M extends BaseModel,P extends BasePresenter<V,M>> extends BaseFragment {

    private boolean isFirst = false;//第一次加载

    private boolean isUserVisible = false;//不可见

    private boolean isLoading = true;//未加载过数据

    P presenter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        if(view!=null){
            isFirst=true;
        }
        lazyLoad();
        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser){
            isUserVisible=true;
        }else {
            isUserVisible=false;
        }
        lazyLoad();
    }

    private void lazyLoad() {
        if(isFirst&&isUserVisible&&isLoading){
            presenter=createPresenter();
            if(presenter!=null){
                presenter.bindView((V) this);
            }
            lazyData();
            isLoading=false;
        }
    }

    protected abstract P createPresenter();

    protected abstract void lazyData();

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if(presenter!=null){
            presenter.destroyView();
            presenter=null;
        }
        isFirst = false;
        isUserVisible = false;
        isLoading = true;
    }
}
